package com.huaxinzhi.print;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.smasher.core.log.ToastUtil;
import com.smasher.core.other.WeakReferenceHandler;

public class PrintProxy implements DefaultLifecycleObserver, IChannel {

    private static final String TAG = "PrintProxy";

    private static final int WHAT_TOAST = 10000;

    private PrintHelper mPrintHelper;
    private WeakReferenceHandler mPrintHandler;
    private String printPath = "/dev/ttyXRM0";
    private int baudRate = 9600;


    private String print_device;

    private String state_connecting;
    private String state_connected;

    private String state_disconnect;
    private String connect_error;

    private String str_cann_printer;

    private String str_disconnect_success;

    private String str_choice_printer_command;

    //#endregion
    boolean isPrintEnable = false;

    private Context mContext;

    public PrintProxy(Context context, String path, int baudRate) {
        mContext = context;
        this.printPath = path;
        this.baudRate = baudRate;
        initString(context);
        mPrintHelper = new PrintHelper();
        mPrintHelper.addObserver(this);
        mPrintHandler = new WeakReferenceHandler(mPrintHelper);
        initBroadcast(context);
    }

    private void initString(Context context) {
        print_device = context.getString(R.string.print_device);
        state_disconnect = context.getString(R.string.str_conn_state_disconnect);
        state_connecting = context.getString(R.string.str_conn_state_connecting);
        state_connected = context.getString(R.string.str_conn_state_connected);
        connect_error = context.getString(R.string.str_conn_state_connect_error);
        str_cann_printer = context.getString(R.string.str_cann_printer);
        str_disconnect_success = context.getString(R.string.str_disconnect_success);
        str_choice_printer_command = context.getString(R.string.str_choice_printer_command);
    }

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {

    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        if (mContext != null) {
            mContext.unregisterReceiver(receiver);
        }
        if (isPrintEnable) {
            mPrintHelper.close();
        }

        if (mPrintHandler != null) {
            mPrintHandler.removeCallbacksAndMessages(null);
            mPrintHandler = null;
        }
    }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
    }

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
        if (isPrintEnable) {
            //获取连接对象是否连接
            DeviceConnFactoryManager[] deviceConnFactoryManagers = DeviceConnFactoryManager.getDeviceConnFactoryManagers();
            for (DeviceConnFactoryManager manager :
                    deviceConnFactoryManagers) {
                if (manager != null && manager.getConnState()) {
                    String connDeviceInfo = mPrintHelper.getConnDeviceInfo();
                    String message = "onStart:" + state_connected + connDeviceInfo;
                    Log.d(TAG, message);
                    break;
                } else {
                    Log.d(TAG, "onStart: " + state_disconnect);
                }
            }
        }

    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
    }

    @Override
    public void unConnect() {
        ToastUtil.info(mContext, str_cann_printer);
    }

    @Override
    public void onDisConnected() {
        ToastUtil.warning(mContext, str_disconnect_success);
    }

    @Override
    public void onPrintError() {
        ToastUtil.error(mContext, str_choice_printer_command);
    }

    /**
     * 注册广播
     * Registration broadcast
     */
    private void initBroadcast(Context context) {
        IntentFilter filter = new IntentFilter();
        //查询打印机缓冲区状态广播，用于一票一控
        filter.addAction(DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE);
        //与打印机连接状态
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);
        ContextCompat.registerReceiver(context, receiver, filter, ContextCompat.RECEIVER_EXPORTED);
    }


    private final BroadcastReceiver receiver = new BroadcastReceiver() {


        private void onPrintState(String message) {

        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null) {
                switch (action) {
                    case DeviceConnFactoryManager.ACTION_CONN_STATE:
                        int state = intent.getIntExtra(DeviceConnFactoryManager.STATE, -1);
                        int deviceId = intent.getIntExtra(DeviceConnFactoryManager.DEVICE_ID, -1);

                        switch (state) {
                            case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:
                                if (deviceId == mPrintHelper.getId()) {
                                    Log.e(TAG, "connection is lost");
                                    String messageDisconnect = print_device + state_disconnect;
                                    mPrintHandler.sendMessage(buildMessage(messageDisconnect));
                                    onPrintState(messageDisconnect);
                                }
                                break;
                            case DeviceConnFactoryManager.CONN_STATE_CONNECTING:
                                String messageConnecting = print_device + state_connecting;
                                mPrintHandler.sendMessage(buildMessage(messageConnecting));
                                onPrintState(messageConnecting);
                                break;
                            case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                                String connDeviceInfo = mPrintHelper.getConnDeviceInfo();
                                String messageConnected = print_device + state_connected + connDeviceInfo;
                                mPrintHandler.sendMessage(buildMessage(messageConnected));
                                onPrintState(messageConnected);
                                break;
                            case DeviceConnFactoryManager.CONN_STATE_FAILED:
                                String messageFailed = print_device + connect_error;
                                mPrintHandler.sendMessage(buildMessage(messageFailed));
                                onPrintState(messageFailed);
                                break;

                        }
                        break;
                    case DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE:
                        mPrintHelper.print();
                        break;

                    default:
                        break;

                }

            }
        }
    };


    public void connectPrint() {
        if (!isPrintEnable) {
            return;
        }

        mPrintHandler.sendMessage(buildMessage(state_connecting));
        mPrintHelper.serialConnectOri(baudRate, printPath);
    }


    private Message buildMessage(String message) {
        Bundle bundle = new Bundle();
        bundle.putString("MESSAGE", message);
        Message messageBean = Message.obtain();
        messageBean.setData(bundle);
        messageBean.what = WHAT_TOAST;
        return messageBean;
    }

}
